package com.base.common.base;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author yanjiaqiang
 * @date 2010-12-28
 * @version $Id: SplitReadWriteLock.java 7 2011-07-15 04:24:04Z JiaqiangYan@gmail.com $
 */
public class SplitReadWriteLock {

	private ReadWriteLock[] locks;

	private int LOCK_NUM;

	public SplitReadWriteLock(int lockNum) {
		super();
		LOCK_NUM = lockNum;
		locks = new ReadWriteLock[LOCK_NUM];
		for (int i = 0; i < LOCK_NUM; i++) {
			locks[i] = new ReentrantReadWriteLock();
		}
	}

	/**
	 * 获取锁,
	 * 
	 * 
	 * @param key
	 * @return
	 */
	public ReadWriteLock getReadWriteLock(Object key) {
		int lockIndex = index(key);
		return locks[lockIndex];
	}

	int index(Object key) {
		int hash = hash(key.hashCode());
		hash = Math.abs(hash);
		return hash % LOCK_NUM;
	}

	public Lock getReadLock(Object key) {
		return getReadWriteLock(key).readLock();
	}

	public Lock getWriteLock(Object key) {
		return getReadWriteLock(key).writeLock();
	}

	// 使用HashMap的hash算法
	int hash(int h) {
		h ^= (h >>> 20) ^ (h >>> 12);
		return h ^ (h >>> 7) ^ (h >>> 4);
	}

}
